package com.spring.dao.impl;

import com.spring.dao.IAccount;
import com.spring.model.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.management.Query;
import java.sql.SQLException;
import java.util.List;
//@Component：作用相当于： <bean id="" class="">，用于创建对象
@Repository("accountDao")
public class AccountImpl implements IAccount {
   @Autowired
    private QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    @Override
    public int save(Account account) {
        String sql="insert into account(uid,money) values(?,?)";
        try {
            return queryRunner.update(sql,account.getUid(),account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Account account) {
        return 0;
    }

    @Override
    public int delete(Account account) {
       String sql="delete from account where id=?";
        try {
            return queryRunner.update(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public Account findById(int id) {
        String sql="select * from account where id=?";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Account.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Account> finaAll() {
        String sql="select * from account";
        List<Account> query =null;
        try {
            query=queryRunner.query(sql, new BeanListHandler<>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return query;
    }

}
